#pragma once
#include"Connection.hpp"
#include<memory>
#include<iostream>

class IO_Processer : public Connection
{
public:
    IO_Processer(int sockfd,ft fts)
    {
        _sockfd = sockfd;
        _ft = fts;
    }

    void Recv()
    {
        while(1)
        {
            char buffer[1024] = {0};
            ssize_t n = recv(_sockfd,buffer,sizeof(buffer)-1,0);
            if(n > 0)
            {
                buffer[n] = 0;
                _inbuffer += buffer;
            }

            else if(n == 0)
            {
                std::cout << "对端关闭" << std::endl;
                return;
            }

            else 
            {
                if(errno == EAGAIN)
                {
                    break;
                }
                else if(errno == EINTR)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }

        }

        _outbuffer = _ft(_inbuffer);
        if(!_outbuffer.empty())
        {
           Send();
        }


    }
    void Send()
    {
        while(1)
        {
            ssize_t n = send(_sockfd,_outbuffer.c_str(),_outbuffer.size(),0);
            if(n > 0)
            {
                _outbuffer.erase(0,n);
                if(_outbuffer.empty())
                {
                    break;
                }
            }
            else if(n == 0)
            {
                break;
            }

            else
            {
                if(errno == EAGAIN)
                {
                    break;
                }
                else if(errno == EINTR)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        if(!_outbuffer.empty())
        {
            uint32_t events = GetEvents();
            SetEvents(events | EPOLLOUT);
        }
        else 
        {
            SetEvents(EPOLLIN | EPOLLET);
        }
    }
    void Expect()
    {

    }


    ~IO_Processer()
    {}

    

};

